
import React, { useEffect, useRef, useState } from "react";
import { IconButton } from "../../../components/IconButton";
import { IconPlus, IconSearch } from "@arco-design/web-react/icon";
import { Conversation, ConversationType } from "../../../domain/im/entity";
import { SessionItem } from "../components/SessionItem";
import { useDispatch, useSelector } from "react-redux";
import { fetchConversationList, changeIndex, clearUnreadCount, refreshConversationByTargetId } from "../../../store/features/conversation";
import { ChatSearch } from "../components/search";
import { Dropdown, Empty, Menu } from "@arco-design/web-react";
import http from "../../../http";
import { openMessage } from "../../../store/features/message";
import { refreshUserInfo } from "../../../store/features/user";
import { fetchGroupInfo } from "../../../store/features/group";
import { fetchGroupMemberInfo } from "../../../store/features/group_member";

export const ChatConversation: React.FC<{}> = () => {

    const { list, current } = useSelector((state: any) => state.conversation.value);
    const dispatch = useDispatch();


    const change = (index: number) => {
        const fetchData = async () => {
            const respones = await http.get("/message/list?targetId=" + list[index].targetId)
            dispatch(openMessage({ messages: respones.data, targetId: list[index].targetId }));
        }
        fetchData();
        dispatch(changeIndex(index))
        dispatch(clearUnreadCount({targetId: list[index].targetId}));
        dispatch(refreshConversationByTargetId({targetId:list[index].targetId , type:list[index].type}))
    }


    useEffect(()=>{
        if(list){
            if(list[current]){
                if(list[current].type == ConversationType.group){
                    console.log(list[current]);
                    // 同步群资料
                    dispatch(fetchGroupInfo(list[current].targetId))
                    // 同步群成员
                    dispatch(fetchGroupMemberInfo(list[current].targetId))
                }
            }
           
        }
    },[list,current])

    useEffect(() => {
        dispatch(fetchConversationList(0))
    }, [])


    return <div className='border-r border-[#E6EBF5] max-w-[290px]'>
        <div className='pr-[16px] flex flex-row justify-between items-center h-[66px] w-full border-b border-b-[#E6EBF5]'>
            <ChatSearch></ChatSearch>
        </div>
        <div className='min-w-[290px] h-[700px]  flex-1 overflow-y-auto '>

            {
                list.length == 0 && <div className="mt-32"><Empty/></div>
            }
            {
               list &&  list.map((item: Conversation, index: number) =>
                    <SessionItem index={index} onClick={change} conversation={item} key={index} select={index === current}></SessionItem>
                )
            }
        </div>
    </div >
}
